package cn.szabadsag.hrm.service.impl;

import cn.szabadsag.hrm.domain.LoginUser;
import cn.szabadsag.hrm.dto.LoginUserDto;
import cn.szabadsag.hrm.exception.Assert;
import cn.szabadsag.hrm.exception.BusinessException;
import cn.szabadsag.hrm.mapper.LoginUserMapper;
import cn.szabadsag.hrm.service.ILoginUserService;
import cn.szabadsag.hrm.util.AjaxResult;
import cn.szabadsag.hrm.util.HttpUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yangcong
 * @since 2022-04-05
 */
@Service
@Slf4j
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {

    @Autowired
    private LoginUserMapper loginUserMapper;

    @Override
    public AjaxResult addLoginUserDto(LoginUserDto loginUserDto) {
        //  保存用户信息
        LoginUser loginUser = loginUserDto.getLoginUser();
        loginUserMapper.insert(loginUser);
        if (loginUserDto.getMealId() != null){
            //  保存用户和套餐中间表信息
            loginUserMapper.saveLoginUserMeals(loginUser.getId(),loginUserDto.getMealId());
        }
        return AjaxResult.me().setResultObj(loginUser.getId());
    }

    /**
     * 更改登录密码
     * @param loginUser
     * @return
     */
    @Override
    public AjaxResult uptByUsername(LoginUser loginUser) {
        //  查询原先的登录信息
        LoginUser loginUserInDB = loginUserMapper.selectByUsername(loginUser.getUsername());
        loginUserInDB.setPassword(loginUser.getPassword());
        loginUserMapper.updateById(loginUserInDB);
        return AjaxResult.me();
    }

    @Value("${hrm.oauth2.passwordurl}")
    private String passwordUrl;

    /**
     * 登录接口
     * @param loginUser
     * @return
     */
    @Override
    public Map<String, String> login(LoginUser loginUser) {

        //  0.前后台用户类型判断
        //  管理系统用户和门户网站的用户
        // 根据用户名查找登录用户信息
        LoginUser loginUserFromDB = selectOne(new EntityWrapper<LoginUser>()
                .eq("username", loginUser.getUsername()));
        Assert.assertNotNull(loginUserFromDB,"用户名不存在");
        //  将包装类型转为基本数据类型
        if (loginUserFromDB.getType().intValue() != loginUser.getType().intValue()){
            throw new BusinessException("非法请求");
        }


        //  1.拼接URL，密码模式获取Token
        String client_id = "";
        String client_secret = "";
        if (loginUser.getType().intValue() == LoginUser.USER_TYPE_SYSTEM){
            client_id = "admin";
            client_secret = "123";
        }else if (loginUser.getType().intValue() == LoginUser.USER_TYPE_WEBSITE){
            client_id = "website";
            client_secret = "123";
        }else {
            throw new BusinessException("非法请求！");
        }
        String username = loginUser.getUsername();
        String password = loginUser.getPassword();
        String okUrl = String.format(passwordUrl, client_id, client_secret, username, password);
        log.info("okUrl====>"+okUrl);
        //  2.发送请求获取Token


        //  3.返回Token
        Map<String, String> map = HttpUtil.sendPost(okUrl);
        log.info("获取到Token {}",map);
        if (map.containsKey("access_token")){
            //  确定access_token过期时间(当前时间+Token有效时长),使用刷新token，refresh_token
            long expireTime = new Date().getTime() + Long.valueOf(String.valueOf(map.get("expires_in"))) * 1000;
            map.put("expireTime",String.valueOf(expireTime));
            return map;
        }else {
            String error_description = map.get("error_description");
            throw new BusinessException(error_description);
        }
    }

















}
